package conpool;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PoolManager {
	
	@Autowired
	PoolConfig poolConfig;
	
	private static PoolManager poolManagerInstance = null;  

	private static List<Pool> poollist = new ArrayList<>();
	
//	private static boolean isInit = false;
	
    public static PoolManager getInstance() {  
    	if (poolManagerInstance == null) {
    		poolManagerInstance = new PoolManager();
    		poolManagerInstance.init();
		}
		return poolManagerInstance;
    }
    
	/* 
	 * 初始化mysql连接池集合,从配置中心获取连接池配置
	 * 
	 */
	private void init() {
		System.out.println("初始化mysql连接池集合成功");
		poolConfig = new PoolConfig();
		poolConfig.init();
		List<Map<String, String>> configList = new ArrayList<>();
		try {
			configList = poolConfig.getConfig();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (Map<String, String> jsonObject : configList) {
			addPool(jsonObject.get("Driver").toString(), 
					jsonObject.get("table").toString(), 
					jsonObject.get("name").toString(), 
					jsonObject.get("password").toString(), 
					jsonObject.get("dataSourceName").toString());
		}
	}
	
	//动态创建连接池,并初始化，加入集合中
	public Pool addPool(String Driver,String table,String name,String password,String dataSourceName) {
		Pool pool = new Pool(Driver, table, name, password, dataSourceName);
		poollist.add(pool);
		return pool;
	}
	
	
	//删除连接池
	public boolean deletePool(String poolName) {
		for (Pool pool : poollist) {
			if (pool.getDataSourceName().equals(poolName)) {
				poollist.remove(pool);
				return true;
			}
		}
		return false;
	}
	
	//根据连接池名称获取连接池
	public Pool getPoolByName(String poolName) {
		for (Pool pool : poollist) {
			System.out.println(pool.getDataSourceName());
			if (pool.getDataSourceName().equals(poolName)) {
				return pool;
			}
		}
		return null;
	}

}
